package com.ep.thirdPlatformProject.system.interceptor;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.ep.thirdPlatformProject.system.aop.LoginRequired;
import com.ep.thirdPlatformProject.system.enums.RoleEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.Method;

/**
 * 系统登陆认证
 *
 */
@Configuration
@RequiredArgsConstructor
public class AuthenticationInterceptor implements HandlerInterceptor {
    public static final String AUTHENTICATION = "SNAIL-JOB-AUTH";
    public static final String NAMESPACE_ID = "SNAIL-JOB-NAMESPACE-ID";

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, @NotNull HttpServletResponse httpServletResponse, @NotNull Object object) throws Exception {
        // 从 http 请求头中取出 token
        String token = httpServletRequest.getHeader(AUTHENTICATION);
        String namespaceId = httpServletRequest.getHeader(NAMESPACE_ID);

        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod handlerMethod)) {
            return true;
        }

        Method method = handlerMethod.getMethod();
        // 检查是否有LoginRequired注释，没有有则跳过认证
        if (!method.isAnnotationPresent(LoginRequired.class)) {
            return true;
        }
        // 执行认证 查看是否存在角色验证
        LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);
        if (loginRequired.required()) {
            RoleEnum role = loginRequired.role();
            if (role == RoleEnum.USER) {
                //todo 自定义逻辑，查看是否需要做权限校验等逻辑
                return false;
            }

            if (role == RoleEnum.ADMIN) {
                return true;
            }

        }

        return true;
    }

    @Override
    public void postHandle(@NotNull HttpServletRequest httpServletRequest,
                           @NotNull HttpServletResponse httpServletResponse,
                           @NotNull Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest httpServletRequest,
                                @NotNull HttpServletResponse httpServletResponse,
                                @NotNull Object o, Exception e) throws Exception {
    }
}
